/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.mzk.kramerius.fedoraaccess.rest;

import cz.mzk.kramerius.commons.DatastreamId;
import cz.mzk.kramerius.commons.Dom4jUtils;
import cz.mzk.kramerius.fedoraaccess.FedoraServer;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.XPath;

/**
 *
 * @author Martin Řehánek <rehan at mzk.cz>
 */
class PurgeRelationshipFedora3_3Operation extends Fedora3_3Operation {

    private static final Logger logger = Logger.getLogger(PurgeRelationshipFedora3_3Operation.class.getName());

    public PurgeRelationshipFedora3_3Operation(FedoraServer fedoraServer) {
        super(fedoraServer);
    }

    public boolean run(String subject, String predicate, String predicatePrefix, String object) {
        try {
            Document relsExt = getDatastreamDissemination(subject, DatastreamId.RELS_EXT);
            removeRelationships(relsExt, predicate, predicatePrefix, object);
            updateDatastreamInlineContent(subject, DatastreamId.RELS_EXT, relsExt);
            return true;
        } catch (Throwable e) {
            logger.log(Level.WARNING, e.getMessage());
            return false;
        }
    }

    public boolean run(String subject, String predicate, String predicatePrefix) {
        return run(subject, predicate, predicatePrefix, null);
    }

    private void removeRelationships(Document relsExt, String predicate, String predicatePrefix, String object) throws Exception {
        XPath relationXpath;
        if (object != null) {
            relationXpath = Dom4jUtils.createXPath("/rdf:RDF/rdf:Description/" + predicatePrefix + ":" + predicate + "[@rdf:resource=\"" + RDF_PID_PREFIX + object + "\"]");
        } else {
            relationXpath = Dom4jUtils.createXPath("/rdf:RDF/rdf:Description/" + predicatePrefix + ":" + predicate);
        }
        System.err.println("xpath: " + relationXpath.getText());
        List<Element> relationElements = relationXpath.selectNodes(relsExt);
        for (Element element : relationElements) {
            element.detach();
        }
        if (relationElements.isEmpty()) {
            throw new Exception("Cannot find any relationship " + relationXpath.toString());
        }
    }
}
